/**
 * @description  生效方式为联合时添加输入内容组件
 * @author zhanghaitao
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { MinusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Select, DatePicker } from 'antd';
import { SelectC, TreeSelectC, InputNumberC } from '../../../../comps';
import moment from 'moment';
const FormItem = Form.Item;
const { Option } = Select;
@Form.create()
class RowForm3 extends PureComponent {
  constructor() {
    super();

    this.state = {
      timeOutGap: 500,
      symbol: [],
      contentType: 1, // 内容类型 1-输入框 2-下拉框 3-树形多选框 4-日期选择框
      contentData: [],
      tag: 1, //内容下拉数据形式 1-发行主体  2-其他
      isMultiple: false, //内容下拉是否支持多选
      defaultData: [], //回填数据
      formItemLayout: {
        labelCol: {
          span: 0,
        },
        wrapperCol: {
          span: 24,
        },
      },
      units: undefined, //根据不同的维度展示不同的单位
      unitPerCent: [
        'valuation_rate_of_return',
        'yield_in_the_past_month',
        'yield_in_recent_three_months',
        'yield_in_the_past_six_months',
        'yearly_one_year_yield',
        'yield_since_establishment',
      ], //单位是百分号的维度
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const { type, selectData, defaultData } = this.props;
    const { unitPerCent } = this.state;
    if (type !== 'add') {
      defaultData.content = defaultData.content && defaultData.content.split(',');
      if (unitPerCent.some((i) => i == defaultData.dimension)) {
        defaultData.content = +defaultData.content[0] * 100;
      }
      if (defaultData.dimension == 'fund_size') {
        //基金规模，单位亿元
        defaultData.content = +defaultData.content[0] / 100000000;
      }
      if (defaultData.dimension == 'circulation_market_value') {
        //流通市值，单位万元
        defaultData.content = +defaultData.content[0] / 10000;
      }
      this.dimensionOnChange(defaultData.dimension);
      this.setState({
        symbol: selectData.flow_filter_operation_symbol,
        defaultData: defaultData,
      });
    }
  }

  // 删除某行
  delete = () => {
    this.props.onDelete(this.props.rowId);
  };

  // 获取数据
  getData3 = () => {
    const {
      form: { validateFields },
    } = this.props;
    const { contentType, unitPerCent } = this.state;
    let data = {};
    validateFields((err, fieldsValue) => {
      if (!err) {
        data = fieldsValue;
        if (contentType == 4) {
          data.content = fieldsValue.content.format('YYYY-MM-DD');
        }
        if (Array.isArray(fieldsValue.content)) {
          data.content = fieldsValue.content.join(',');
        }
        if (unitPerCent.some((i) => i == fieldsValue.dimension)) {
          data.content = fieldsValue.content / 100;
        }
        if (fieldsValue.dimension == 'fund_size') {
          //基金规模，单位亿元
          data.content = fieldsValue.content * 100000000;
        }
        if (fieldsValue.dimension == 'circulation_market_value') {
          //流通市值，单位万元
          data.content = fieldsValue.content * 10000;
        }
      }
    });
    return data;
  };

  // 内容模糊搜索
  changeContent = (value) => {
    const { timeOutGap } = this.state;
    const { dispatch } = this.props;
    if (value) {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        dispatch({
          type: 'couponPoolApprovalM/searchContent',
          payload: {
            value: value,
          },
        });
      }, timeOutGap);
    }
  };

  changeTreeData = (arr) => {
    let tempArr = [];
    arr.forEach((item) => {
      tempArr.push({
        value: item.code,
        title: item.value,
        selectable: !item.children?.length,
        children: this.changeTreeData(item.children || []),
      });
    });
    return tempArr;
  };

  // 响应维度点击
  dimensionOnChange = (e) => {
    const {
      form: { resetFields },
      globalM: {
        dataDictionary: { CREDITBND_MONITOR_BONDTYPEI = [] },
      },
      couponPoolApprovalM: { symbolData1, symbolData2 },
      poolType,
      selectData,
      dispatch,
    } = this.props;
    const bondTypeList = this.changeTreeData(CREDITBND_MONITOR_BONDTYPEI);
    resetFields(['content', 'symbol']);
    if (poolType == 'bond') {
      //债券
      if (e == 'bond_type') {
        // 债券类型
        this.setState({
          symbol: symbolData1,
          contentData: bondTypeList,
          contentType: 3,
          isMultiple: true,
        });
      } else if (e == 'issuer') {
        // 发行主体
        this.setState({
          symbol: symbolData2,
          tag: 1,
          contentType: 2,
          isMultiple: true,
        });
      } else if (e == 'subject_rating' || e == 'debt_rating') {
        //主体评级、债项评级
        let newData = [];
        selectData.RATERANGESTART_END.map((item) => {
          newData.push({ title: item.value, value: item.code });
        });
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentData: newData,
          tag: 2,
          contentType: 2,
          isMultiple: false,
        });
      } else {
        if (e == 'remaining_period') {
          //剩余期限
          this.setState({ units: 'Y' });
        } else if (e == 'valuation_rate_of_return') {
          this.setState({ units: '%' });
        } else {
          this.setState({ units: '元' });
        }
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 1,
        });
      }
    } else if (poolType == 'fund') {
      //基金
      if (e == 'fund_type') {
        //基金类型
        let newData = [];
        selectData.fund_Trade_FundStatus.map((item) => {
          newData.push({ title: item.value, value: item.code });
        });
        this.setState({
          symbol: symbolData1,
          contentData: newData,
          tag: 2,
          contentType: 2,
          isMultiple: true,
        });
      } else if (e == 'startdate') {
        //成立日期，内容为日期选择框
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 4,
        });
      } else {
        if (e == 'fund_size') {
          this.setState({ units: '亿' });
        } else {
          this.setState({ units: '%' });
        }
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 1,
        });
      }
    } else {
      //股票
      if (e == 'FINDUCODE_SW') {
        //申万一级
        this.setState({ symbol: symbolData1 });
        dispatch({
          type: 'couponPoolApprovalM/searchContentOne',
          payload: {},
          callback: (data) => {
            if (data) {
              this.setState({
                contentData: data,
                tag: 2,
                contentType: 2,
                isMultiple: true,
              });
            }
          },
        });
      } else if (e == 'SINDUCODE_SW') {
        //申万二级
        this.setState({ symbol: symbolData1 });
        dispatch({
          type: 'couponPoolApprovalM/searchContentTwo',
          payload: {},
          callback: (data) => {
            if (data) {
              this.setState({
                contentData: data,
                tag: 2,
                contentType: 2,
                isMultiple: true,
              });
            }
          },
        });
      } else {
        if (e == 'circulation_market_value') {
          this.setState({ units: '万' });
        } else if (e == 'P/B_ratio' || e == 'P/E_ratio') {
          this.setState({ units: undefined });
        } else {
          this.setState({ units: '元' });
        }
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 1,
        });
      }
    }
  };

  // 渲染查询表单
  formRender = () => {
    const {
      form: { getFieldDecorator },
      type,
      colsNum,
      selectData,
      poolType,
      couponPoolApprovalM: { issuer },
    } = this.props;
    const { symbol, tag, contentType, isMultiple, contentData, defaultData, formItemLayout, units } = this.state;
    const dimension =
      poolType == 'bond' ? selectData.flow_filter_dimension_bond : poolType == 'fund' ? selectData.flow_filter_dimension_fund : selectData.flow_filter_dimension_stock;
    //计算每列宽度
    const styleRow = {};
    const styleRow2 = {};
    if (colsNum) {
      const width = parseFloat(95 / (colsNum - 1)) + '%';
      styleRow.width = width;
      styleRow.paddingRight = '10px';
      styleRow2.width = width;
      styleRow2.paddingRight = '10px';
      styleRow2.visibility = 'hidden';
    }
    return (
      <div style={{ display: 'flex' }}>
        <div style={styleRow2}></div>
        <div style={styleRow}>
          <FormItem>
            {getFieldDecorator(`dimension`, {
              initialValue: type !== 'add' ? defaultData.dimension : '',
              rules: [{ required: true, message: ` ` }],
            })(
              <Select style={{ width: '100%' }} disabled={type == 'see' ? true : false} onChange={this.dimensionOnChange}>
                {dimension
                  ? dimension.map((item) => {
                      return (
                        <Option key={item.id} value={item.code}>
                          {item.value}
                        </Option>
                      );
                    })
                  : null}
              </Select>,
            )}
          </FormItem>
        </div>
        <div style={styleRow}>
          <FormItem>
            {getFieldDecorator(`symbol`, {
              initialValue: type !== 'add' ? defaultData.symbol : '',
              rules: [{ required: true, message: ` ` }],
            })(
              <Select style={{ width: '100%' }} disabled={type == 'see' ? true : false}>
                {symbol
                  ? symbol.map((item) => {
                      return (
                        <Option key={item.id} value={item.code}>
                          {item.value}
                        </Option>
                      );
                    })
                  : null}
              </Select>,
            )}
          </FormItem>
        </div>
        <div style={styleRow}>
          {contentType == 1 ? (
            <InputNumberC
              form={this.props.form}
              dataIndex={'content'}
              initialValue={type !== 'add' ? defaultData.content : null}
              disabled={type == 'see' ? true : false}
              formItemLayout={formItemLayout}
              rules={[{ required: true, message: '' }]}
              unit={units}
              precision={4}
            />
          ) : contentType == 3 ? (
            <TreeSelectC
              form={this.props.form}
              dataIndex={'content'}
              formItemLayout={formItemLayout}
              dataSource={contentData}
              rules={[{ required: true, message: '' }]}
              allowClear={true}
              isMultiple={true}
              treeDefaultExpandAll={true}
              style={{ width: '100%' }}
              disabled={type == 'see' ? true : false}
              initialValue={type !== 'add' ? defaultData.content : []}
              treeCheckable={true}
              showCheckedStrategy={'SHOW_CHILD'}
              maxTagCount={0}
            />
          ) : contentType == 4 ? (
            <FormItem>
              {getFieldDecorator(`content`, {
                initialValue: type !== 'add' ? moment(defaultData.content[0]) : '',
                rules: [{ required: true, message: ` ` }],
              })(<DatePicker style={{ width: '100%' }} disabled={type == 'see' ? true : false} />)}
            </FormItem>
          ) : tag == 1 ? (
            <FormItem>
              {getFieldDecorator(`content`, {
                initialValue: type !== 'add' ? defaultData.content : '',
                rules: [{ required: true, message: ` ` }],
              })(
                <Select style={{ width: '100%' }} filterOption={false} showSearch onSearch={this.changeContent} disabled={type == 'see' ? true : false}>
                  {issuer
                    ? issuer.map((item) => {
                        return (
                          <Option key={item} value={item}>
                            {item}
                          </Option>
                        );
                      })
                    : null}
                </Select>,
              )}
            </FormItem>
          ) : (
            <SelectC
              form={this.props.form}
              dataIndex={'content'}
              rules={[{ required: true, message: ' ' }]}
              allowClear={true}
              dataSource={contentData}
              isMultiple={isMultiple}
              disabled={type == 'see' ? true : false}
              initialValue={type !== 'add' ? defaultData.content : undefined}
            />
          )}
        </div>
        {type == 'see' ? null : (
          <div style={{ width: '45px', textAlign: 'center' }}>
            <a onClick={this.delete}>
              <MinusCircleOutlined />
            </a>
          </div>
        )}
      </div>
    );
  };

  render() {
    return this.formRender();
  }
}

export default connect(({ couponPoolApprovalM, globalM }) => ({
  couponPoolApprovalM,
  globalM,
}))(RowForm3);
